/*
 * #%L
 * SwiftUICommonUtilities
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package com.linkwithweb.products.swiftui.utils;

import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.linkwithweb.products.swiftui.export.excel.FileDataSource;

/**
 * @author ashwin kumar
 * 
 */
@Service("mailUtils")
public class MailUtils {
	
	private static final transient Log logger = LogFactory.getLog(MailUtils.class);
	public static final String ERROR_LIST_VELOCITY_TEMPLATE = "errorListTemplate.vm";
	public static final String EMAIL_SENDER = "LedSupport@boa.com";

	/**
	 * 
	 */
	public MailUtils() {
	}

	@Autowired
	@Qualifier(value = "velocityEngine")
	private VelocityEngine velocityEngine;

	@Autowired
	@Qualifier(value = "javaMailSender")
	private JavaMailSender javaMailSender;

	public JavaMailSender getJavaMailSender() {
		if (javaMailSender == null) {
			javaMailSender = (JavaMailSender) ServiceLocator.getService("javaMailSender");
		}
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public VelocityEngine getVelocityEngine() {
		if (velocityEngine == null) {
			velocityEngine = (VelocityEngine) ServiceLocator.getService("velocityEngine");
		}
		return velocityEngine;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	/**
	 * @param messages
	 * @param originalFilename
	 * @param url
	 * @return
	 */
	private String generateEmailMessage(List<String> messages, Map<String, String> parameters) {
		String msg_body = "";

		try {
			msg_body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, ERROR_LIST_VELOCITY_TEMPLATE,
					"UTF-8", parameters);
		} catch (VelocityException e) {
			e.printStackTrace();
		}

		return msg_body;
	}

	/**
	 * @param toEmailAddress
	 * @param message
	 * @param subject
	 * @throws MailException
	 */
	public void sendEmail(final String toEmailAddress, final String message, final String subject) throws MailException {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
				mimeMessageHelper.setTo(toEmailAddress);
				mimeMessageHelper.setFrom(EMAIL_SENDER);
				mimeMessageHelper.setSubject(subject);
				mimeMessageHelper.setText(message);
			}
		};
		getJavaMailSender().send(preparator);
	}

	/**
	 * 
	 * To send mail with attachments..
	 * 
	 * @param toEmailAddress
	 * @param messageContent
	 * @param subject
	 * @param myDataSource
	 */
	public void sendMailWithAttachments(String toEmailAddress, String messageContent, String subject, String fileName,
			String filePath, String fromAddress) {
		try {
			boolean debug = false;
			/*
			 * Properties props = new Properties();
			 * props.setProperty("mail.transport.protocol", "smtp");
			 * props.setProperty("mail.host", "mymail.server.org");
			 * props.setProperty("mail.user", "emailuser");
			 * props.setProperty("mail.password", "");
			 * 
			 * Session mailSession = Session.getDefaultInstance(props, null);
			 * mailSession.setDebug(debug);
			 */
			// Transport transport = mailSession.getTransport();

			// MimeMessage message = new MimeMessage(mailSession);
			MimeMessage message = this.javaMailSender.createMimeMessage();
			message.setSubject(subject);
			message.setFrom(new InternetAddress(fromAddress));
			MimeBodyPart textPart = new MimeBodyPart();
			textPart.setContent(messageContent, "text/html");

			MimeBodyPart attachFilePart = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(filePath);
			attachFilePart.setDataHandler(new DataHandler(fds));
			attachFilePart.setFileName(fileName);

			Multipart mp = new MimeMultipart();
			mp.addBodyPart(textPart);
			mp.addBodyPart(attachFilePart);

			message.setContent(mp);

			for (String emailAddress : toEmailAddress.split(",")) {
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
			}

			getJavaMailSender().send(message);
			/*
			 * transport.connect(); transport.sendMessage(message,
			 * message.getRecipients(Message.RecipientType.TO));
			 * transport.close();
			 */
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("Error while sending mail..", e);
		}
	}

}
